local desc_1v1 = [[
  # 无限火力4v4模式简介

  无限火力+4v4模式
  和队友一起赢得胜利吧
  ___
  ## 所有角色固定为8血
  ## 游戏开始时，获得一个随机技能
  ## 全场每累计造成10点伤害，获得一个随机技能
  启用双将时不再次获得原始技能！


]]

-- FIXME: Disable same convert by param or extra data
local function rm(generals, g)
  local gt = Fk.generals[g].trueName
  for i, v in ipairs(generals) do
    if Fk.generals[v].trueName == gt then
      table.remove(generals, i)
      return
    end
  end
end

--
--技能获得
local function reward_Newskill(room,players)
  local room=room
  local req = Request:new(players, "CustomDialog")
    req.focus_text = "无限火力"
  for _, player in ipairs(players) do
  local existingGenerals = {}
  table.forEach(room.players, function(p)
    table.insertTable(existingGenerals, {p.general, p.deputyGeneral})
  end)
  local generals = table.map(Fk:getGeneralsRandomly(10, Fk:getAllGenerals(), existingGenerals,
    (function(p) return false end)), function(g) return g.name end)
  generals = table.random(generals, math.min(4, #generals))
  local skills = {}
  local choices = {}
  for _, general_name in ipairs(generals) do
local general = Fk.generals[general_name]
local g_skills = {}
--加载技能
for _, skill in ipairs(general.skills) do
    table.insertIfNeed(g_skills, skill.name)

end
for _, s_name in ipairs(general.other_skills) do
  local skill = Fk.skills[s_name]

    table.insertIfNeed(g_skills, skill.name)

end
table.insertIfNeed(skills, g_skills)
if #choices == 0 and #g_skills > 0 then
  choices = {g_skills[1]}
end
  end
  

if #choices > 0 then
  req:setData(player, {
    path = "packages/utility/qml/ChooseGeneralSkillsBox.qml",
    data = {
      generals, skills, 1, 1, "jbsfire__reward",false
    },
  })
  local s=table.random(skills, 1)[1]
  req:setDefaultReply(player,s[1])
end

--结束循环
end


for _, p in ipairs(players) do
  local choice = req:getResult(p)
  room:handleAddLoseSkills(p, choice, nil)
  --p:drawCards(1)
end

end

--buff表

local m_1v1_getLogic = function()
  local m_1v1_logic = GameLogic:subclass("fire4v4_logic")

  
  --身份分配
  function m_1v1_logic:assignRoles()
    local room = self.room
    local n = #room.players
    if room:getSettings('enableDeputy')  then
    local roles = table.random {
      { "loyalist", "rebel", "rebel", "loyalist" , "loyalist",  "rebel", "rebel","loyalist"},
      { "rebel", "loyalist", "loyalist", "rebel","rebel", "loyalist" , "loyalist","rebel"},
    }

  
    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end
    self.start_role = roles[1]
    else
      for i = 1, n do
        local p = room.players[i]
        if i%2~=0 then
          p.role ="loyalist"
        else
          p.role = "rebel"
        end
        room:setPlayerProperty(p, "role_shown", true)
        room:broadcastProperty(p, "role")
      end
      self.start_role = room.players[1].role
    end

    room.players[1].role = "lord"

    -- for adjustSeats
    -- for adjustSeats
  end
  function m_1v1_logic:chooseGenerals()
    local room = self.room
    local generalNum = room:getSettings('generalNum')
    local n = room:getSettings('enableDeputy') and 1 or 1
    local lord = room:getLord()
    local lord_generals = {}
  
    if lord ~= nil then
      room.current = lord
      room:setBanner("@[:]jbsfire_rule","jbsghost-intro")
      room:setBanner("@jbsfire_assignment","jbsfire-assign5")
      room:setTag("jbsfire_as",10)
      room:setBanner("@jbsfire_assignmentprocess","0 / 10")
    end
    local nonlord = room.players
    local generals = room:getNGenerals(#nonlord * generalNum)
    table.shuffle(generals)
    local req = Request:new(nonlord,  "AskForGeneral")
    for i, p in ipairs(nonlord) do

      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      req:setData(p, { arg, n })
      req:setDefaultReply(p, table.random(arg, n))
    end
  


    local selected = {}
    for _, p in ipairs(nonlord) do
      local result = req:getResult(p)
      local general, deputy = result[1], result[2]
      table.insertTableIfNeed(selected, result)
      room:findGeneral(general)
      room:findGeneral(deputy)
      room:prepareGeneral(p, general, deputy)
    end
  
    generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
    room:returnToGeneralPile(generals)
  
    room:askForChooseKingdom(nonlord)
  end

  --[[
  function m_1v1_logic:chooseGenerals()
      local room = self.room
      room:setBanner("@jbsfire","jbsfire-intro")
      local generalNum = room:getSettings('generalNum')
      --local n = room:getSettings('enableDeputy') and 2 or 1
      local n=1    
      local nonlord = room.players
      local generals = room:getNGenerals(#nonlord * generalNum)
      table.shuffle(generals)
      for i, p in ipairs(nonlord) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        p.request_data = json.encode{ arg, n }
        p.default_reply = table.random(arg, n)
      end
    
      room:notifyMoveFocus(nonlord, "AskForGeneral")
      room:doBroadcastRequest("AskForGeneral", nonlord)
    
      local selected = {}
      for _, p in ipairs(nonlord) do
        if p.general == "" and p.reply_ready then
          local general_ret = json.decode(p.client_reply)
          local general = general_ret[1]
          local deputy = general_ret[2]
          table.insertTableIfNeed(selected, general_ret)
          room:setPlayerGeneral(p, general, true, true)
          room:setDeputyGeneral(p, deputy)
        else
          room:setPlayerGeneral(p, p.default_reply[1], true, true)
          room:setDeputyGeneral(p, p.default_reply[2])
        end
        p.default_reply = ""
      end
    
    
      room:askForChooseKingdom(nonlord)
  end
  --]]

  function m_1v1_logic:broadcastGeneral()--血量置为8血
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      p.maxHp =8
      p.hp = 8
      p.shield = 0
      --room:broadcastProperty(p, "role")     
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
      room:broadcastProperty(p, "deputyGeneral")
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end
  function m_1v1_logic:attachSkillToPlayers()
    local room = self.room
    if room:getSettings('enableDeputy') then
      return true
    end
    local players = room.players
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) and not (player.role == "lord" and player.role_shown and room:isGameMode("role_mode")) then
        return
      end
  
      if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
        return
      end
  
      room:handleAddLoseSkills(player, skillName, nil, false, true)
      self:trigger(fk.EventAcquireSkill, player, skill)
    end
    for _, p in ipairs(room.alive_players) do
      local skills = Fk.generals[p.general].skills
      for _, s in ipairs(skills) do
        addRoleModSkills(p, s.name)
      end
      for _, sname in ipairs(Fk.generals[p.general].other_skills) do
        addRoleModSkills(p, sname)
      end
  
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        skills = deputy.skills
        for _, s in ipairs(skills) do
          addRoleModSkills(p, s.name)
        end
        for _, sname in ipairs(deputy.other_skills) do
          addRoleModSkills(p, sname)
        end
      end
    end
  end


  return m_1v1_logic
end




local m_1v1_rule = fk.CreateTriggerSkill{
  name = "#jbsfire4v4_rule",
  priority = 0.001,
  refresh_events = {fk.Damage,fk.GameStart,fk.GameOverJudge},
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local players=room.alive_players
      room:doBroadcastNotify("ShowToast", "清明时节雨纷纷,路上行人欲断魂")
      reward_Newskill(room,players)
      --[[
      local existingGenerals = {}
      --筛选
        table.forEach(room.players, function(p)
          table.insert(existingGenerals,p.general)
        end)
        for _, p in ipairs(players) do
          local glists=existingGenerals
          local glist =table.random(glists,1)[1]
          if glist then
          p.deputyGeneral =glist
          room:broadcastProperty(p, "deputyGeneral")
          local skill_name = Fk.generals[glist]:getSkillNameList()
          room:handleAddLoseSkills(p, skill_name, nil, false, false)
  
          end
  
        end
        --]]
      --执行奖惩
    elseif event==fk.Damage then
    local assign=room:getTag("jbsfire_as")
    local count=room:getTag("jbsfire_count") or 0

    count=count+data.damage
    room:setBanner("@jbsfire_assignmentprocess",tostring(count).." / "..assign)
    if count>=assign then
      room:doBroadcastNotify("ShowToast", "任务完成，请接受奖励！")
      --room:setTag("jbsfire_as",10)
      room:setBanner("@jbsfire_assignmentprocess","0".." / "..assign)
      local players=room.alive_players
      room:setTag("jbsfire_count",0)
      reward_Newskill(room,players)
    else
      room:setTag("jbsfire_count",count)
    end

    

  elseif event == fk.GameOverJudge then
    room:setTag("SkipGameRule", true)
    if #room.alive_players == 1 then
      local winner = Fk.game_modes[room:getSettings('gameMode')]:getWinner(player)
      if winner ~= "" then
        room:gameOver(winner)
        return true
      end
    end

    end


  end,
}






local m_1v1_mode = fk.CreateGameMode{
  name = "jbsfire4v4_mode",
  minPlayer = 2,
  maxPlayer = 8,
  rule = m_1v1_rule,
  logic = m_1v1_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 2 min", passed = playedTime >= 120 },
    { text = "2v2: left you alive", passed = table.find(Fk:currentRoom().players, function(p)
      return p.role == Self.role and p.dead
    end) and true } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
}
-- extension:addGameMode(m_1v1_mode)
Fk:loadTranslationTable{
  ["jbsfire4v4_mode"] = "无限火力4v4",
  [":jbsfire4v4_mode"] = desc_1v1,
}

return m_1v1_mode
